import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/pages/main/logic.dart';
import 'package:yp/services/api.dart';
import 'dart:convert' as convert;

import '../../../helper.dart';
import '../../../router.dart';
import 'state.dart';

class DecorationActivitiesLogic extends GetxController {
  // final MainAppLogic MainAppLogics = Get.put(MainAppLogic());
  final MainLogic mainLogic = Get.put(MainLogic());
  final state = DecorationActivitiesState();

  @override
  void onInit() {
    super.onInit();


  }

  @override
  void onReady() {
    super.onReady();
    getDecoData(Get.arguments['linktarget']);
    return;
    var params = {
      'from_sign': 1, //死值,移动端专用
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'tmpl_num_id': Get.arguments['linktarget'] ?? '', //模板ID
      // 'ec_shop_num_id': SpUtil.getInt('storeShopNum'), //店铺ID
      "ec_shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
    }; // channelPageTemplate
    Api.channelPageTemplate(params).listen((event) {
      print(' ===== 频道页模板详情：=====   event = $event');
      if (event['code'] == 0) {
        state.titleString = event['instance']['tmpl_title'];
        List list = event['instance']['data'];
        if (event['instance']['data'] != null) {
          List list1 = [];
          for (int i = 0; i < list.length; i++) {
            var map = list[i];
            if (map['widgets_data_status'] == 1) {
              list1.add(map);
            }
          }
          state.templateList = list1;
          processingList();
        } else {
          state.templateList = [];
        }
      }
      update();
    });
    keFu();
  }


  void getDecoData(_linkTarget) {
    state.titleString = '';
    update();
    var params = {
      'from_sign': 1, //死值,移动端专用
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'tmpl_num_id': _linkTarget ?? '', //模板ID
      // 'ec_shop_num_id': SpUtil.getInt('storeShopNum'), //店铺ID
      "ec_shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
    }; // channelPageTemplate
    Api.channelPageTemplate(params).listen((event) {
      print(' ===== 频道页模板详情：=====   event = $event');
      if (event['code'] == 0) {
        state.titleString = event['instance']['tmpl_title'];
        state.tmpl_desc = event['instance']['tmpl_desc'];
        state.image_id = event['instance']['image_id'];
        state.tmpl_id = event['instance']['tmpl_id'];
        state.currentShopId =event['instance']['ec_shop_num_id'];
        List list = event['instance']['data'];
        if (event['instance']['data'] != null) {
          List list1 = [];
          for (int i = 0; i < list.length; i++) {
            var map = list[i];
            if (map['widgets_data_status'] == 1) {
              list1.add(map);
            }
          }
          state.templateList = list1;
          processingList();
        } else {
          state.templateList = [];
        }
      }
      update();
    });
    keFu();

  }
  void processingList() {
    state.goodsList = [];
    state.angleInformationList = [];
    state.couponsList = [];
    state.templateList.map((itemModel) {
      if (itemModel['widgets_sign'] == 4) {
        refreshList(dataMap: itemModel);
      }
      if (itemModel['widgets_sign'] == 8) {
        homeCoupon(dataMap: itemModel);
      }
    }).toList();
  }

  void refreshList({
    Map<String, dynamic> dataMap,
  }) {
    var map = convert.jsonDecode(dataMap['widgets_data_params']);
    var _pageSize=dataMap['style'].length;
    // if(map['nublayout'] != 'no' && map['nubnub'] != null && map['nubnub'] != '')
    //   {
    //     _pageSize=int.parse(map['nubnub']);
    //   }
    var params = {
      'use_platform': '2',
      // 'shop_id': SpUtil.getInt('storeShopNum'),
      "shop_id": dataMap['ec_shop_num_id'],
      'shop_num_id': dataMap['ec_shop_num_id'],
      'page_no': '1',
      'page_size': _pageSize,
      'nublayout': map['nublayout'],
      'nubnub': map['nubnub'],
      'widgets_data_id': dataMap['widgets_data_id'],
      'sold_type': map['sold_type'],
      'access_token': SpUtil.getString('token'),
      'customer_type': 3,
      'user_num_id': SpUtil.getInt('empeNumId'),
      // 'prv_num_id': '',
      // 'city_num_id': '',
      // 'city_area_num_id': '',
    };
    Api.optionalGoods(params).listen((event) {
      if (event['code'] == 0) {
        Map<String, dynamic> goodsMap = {
          'widgets_data_id': dataMap['widgets_data_id'],
          'listMap': event['lists'],
        };
        print('optionalGoods goodsMap length is:${goodsMap['listMap'].length}');
        state.goodsList.add(goodsMap);
        List goodLists = [];
        List styleList = event['lists'];
        styleList.forEach((element) {
          goodLists.add('${element['default_item_num_id']}');
        });
        if (goodLists.length == 0) {
          Map<String, dynamic> goodsMap = {
            'widgets_data_id': dataMap['widgets_data_id'],
            'listMap': [],
          };
          state.angleInformationList.add(goodsMap);
        } else {
          var params1 = {
            // 'shop_id': SpUtil.getInt('storeShopNum'),
            "shop_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
            // 'super_ec_shop_num_id': SpUtil.getInt('storeShopNum'), //店铺ID
            "super_ec_shop_num_id":
                SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
            'item_num_id_list': goodLists,
          };
          Api.shopTag(params1).listen((event) {
            // print(' 商品列表 角标信息  ======================  event = $event');
            if (event['code'] == 0) {
              Map<String, dynamic> goodsMap = {
                'widgets_data_id': dataMap['widgets_data_id'],
                'listMap': event['tag_list'] ?? [],
              };
              print('shopTag goodsMap length is:${goodsMap['listMap'].length}');
              state.angleInformationList.add(goodsMap);
            }
            update();
          });
        }
      }
      update();
    });
  }

  // 下拉刷新
  void refreshData() {
    state.templateList = [];
    var params = {
      'from_sign': 1, //死值,移动端专用
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'tmpl_num_id': Get.arguments['linktarget'] ?? '', //模板ID
      // 'ec_shop_num_id': SpUtil.getInt('storeShopNum'), //店铺ID
      "ec_shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
    }; // channelPageTemplate
    Api.channelPageTemplate(params).listen((event) {
      print(' ===== 频道页模板详情：=====   event = $event');
      if (event['code'] == 0) {
        state.titleString = event['instance']['tmpl_title'];
        List list = event['instance']['data'];
        if (event['instance']['data'] != null) {
          List list1 = [];
          for (int i = 0; i < list.length; i++) {
            var map = list[i];
            if (map['widgets_data_status'] == 1) {
              list1.add(map);
            }
          }
          state.templateList = list1;
          processingList();
        } else {
          state.templateList = [];
        }
      }
      state.refreshController.refreshCompleted();
      update();
    });
  }
  // // 添加购物车
  // void addShoppingCart({
  //   String ec_shop_num_id,
  //   String item_num_id,
  //   String style_num_id,
  //   String ec_style_num_id,
  // }) {
  //   var params = {
  //     "use_platform": 2, //平台
  //     "usr_num_id": SpUtil.getInt('empeNumId'), //会员ID
  //     "emp_num_id": 0, //操作员ID,移动端无属性,默认传0
  //     "channel_num_id": 99, //订单渠道：小程序 98，App 99
  //     "quantity": 1.0, //数量
  //     "ec_shop_num_id": ec_shop_num_id, //店铺编码
  //     "item_num_id": item_num_id, //商品编码
  //     "style_num_id": style_num_id, //款式编码
  //     "ec_style_num_id": ec_style_num_id, //款式唯一编码
  //     'access_token': SpUtil.getString('token'),
  //     // "prv_num_id": 320000, //省编码
  //     // "city_num_id": 320500, //市编码
  //     // "city_area_num_id": 320583, //区编码
  //   };
  //   Api.addShoppingCart(params).listen((event) {
  //     if (event['code'] == 0) {
  //       toast('添加成功');
  //       MainAppLogics.getCartNum();
  //     } else {
  //       toast('添加失败');
  //     }
  //   });
  // }

  // 获取客服信息
  void keFu() {
    print('获取客服信息 ======== 获取客服信息11111111');
    Api.MaterialGoodsSelect1({"config_name": "platform_ec_shop_num_id"})
        .listen((event) {
      print('获取客服信息 ======== 获取客服信息 ********  event = $event');
      var configValue = event["config_value"];
      Api.getAccessID(configValue.toString()).listen((event) {
        print('获取客服信息 ======== 获取客服信息  event = $event');
        // state.accessID = event["access_id"];
        state.keFuString = event['access_id'];
        update();
      });
    });
  }
  void homeCoupon({
    Map<String, dynamic> dataMap,
  }) {
    var map = convert.jsonDecode(dataMap['widgets_data_params']);
    var list = dataMap['style'];
    List styleList = [];
    list.forEach((element) {
      styleList.add(element['style_num_id']);
    });
    if (styleList.length == 0) {
      Map<String, dynamic> goodsMap = {
        'widgets_data_id': dataMap['widgets_data_id'],
        'listMap': [],
      };
      state.couponsList.add(goodsMap);
    } else {
      var params = {
        'usr_num_id': SpUtil.getInt('empeNumId'),
        'activityids': styleList,
      };
      // print('=====----===========-------------  params = $params');
      Api.homeCoupon(params).listen((event) {
        // print('+++++++++++ 优惠券 *********** event = $event');
        if (event['code'] == 0) {
          Map<String, dynamic> goodsMap = {
            'widgets_data_id': dataMap['widgets_data_id'],
            'listMap': event['card_tickets'] ?? [],
          };
          state.couponsList.add(goodsMap);
        }
        update();
      });
    }
  }
 void getCouponOrToCouponGoodsList({
  Map<String, dynamic> couponModel,
  }){
    var couponId=couponModel['linktarget'];
    var params = {
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'activityids': [couponId,],
    };
    // print('=====----===========-------------  params = $params');
    Api.homeCoupon(params).listen((event) {
      // print('+++++++++++ 优惠券 *********** event = $event');
      if (event['code'] == 0 && event['card_tickets']!=null && event['card_tickets'].length==1) {
        var model=event['card_tickets'][0];
        if (model['relation'] == 0) {
          if (model['stock_qty'] > 0) {
            var params = {
              'use_platform': 2,
              'coupon_num_id': model['series'].toString(),
              'usr_num_id': SpUtil.getInt('empeNumId'),
              'access_token': SpUtil.getString('token'),
              'qsource': 301,
              'relation_indate': "永久有效",
              'user_num_id': SpUtil.getInt('empeNumId'),
            };
            Api.getCoupon(params).listen((event) {
              if (event['code'] == 0) {
                toast('领券成功');
                model['relation'] = 1;
              }
            });
          } else {
            toast('库存不足');
          }
        } else {
          if (model['use_begin_date'] != '' &&
              model['use_begin_end'] != '' &&
              model['use_begin_date'] != null &&
              model['use_begin_end'] != null) {
            var startDate = DateTime.tryParse(model['use_begin_date']);
            var endDate = DateTime.tryParse(model['use_begin_end']);
            var disable = (DateTime.now().isBefore(startDate)) ||
                (DateTime.now().isAfter(endDate));
            if (disable) {
              toast('未到优惠券使用时间');
              return false;
            }
          }
          Get.toNamed(RouteConfig.couponGoodsList, arguments: {
            'coupon_id': model['series'],
          });
        }
      }
      update();
    });
  }
}
